﻿using System;
using System.Windows;
using System.Windows.Controls;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Symbols;
using ESRI.ArcGIS.Client.Tasks;

namespace DllShepherd.EsriSilverlightApi.GettingStarted
{
    public partial class SpatialQuery : UserControl
    {
        private bool _selectionMode = false;
        private readonly GraphicsLayer _selectionGraphicsLayer;

        public SpatialQuery()
        {
            InitializeComponent();

            _selectionGraphicsLayer = new GraphicsLayer();
            MapControl.Layers.Add(_selectionGraphicsLayer);
        }

        private void PointButton_Click(object sender, RoutedEventArgs e)
        {
            _selectionMode = true;
            StatusTextBlock.Text = "Select by clicking at point location";
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            _selectionMode = false;
            StatusTextBlock.Text = "Cancel Selection Tools";
        }

        private void MapControl_MouseClick(object sender, Map.MouseEventArgs mouseEventArgs)
        {
            if (_selectionMode)
                QueryContainingGeometry(mouseEventArgs.MapPoint);
        }

        private void QueryContainingGeometry(Geometry geometry)
        {
            _selectionGraphicsLayer.ClearGraphics();

            var queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
            queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted;
            queryTask.Failed += (sender, args) => MessageBox.Show("Query failed: " + args.Error);

            var query =
                new Query
                {
                    Geometry = geometry,
                    ReturnGeometry = true,
                    OutFields = new OutFields{"*"},
                    OutSpatialReference = MapControl.SpatialReference
                };

            queryTask.ExecuteAsync(query);
        }

        private void QueryTask_ExecuteCompleted(object sender, QueryEventArgs args)
        {
            var featureSet = args.FeatureSet;

            if (featureSet == null || featureSet.Features.Count == 0)
            {
                MessageBox.Show("No features returned from query");
                return;
            }

            var minimumSquareMiles = int.MaxValue;
            foreach (var feature in featureSet.Features)
            {
                feature.Symbol = LayoutRoot.Resources["FirstStateSymbol"] as FillSymbol;
                _selectionGraphicsLayer.Graphics.Add(feature);
                minimumSquareMiles = Math.Min(minimumSquareMiles, (int) feature.Attributes["SQMI"]);
            }

            QueryByArea(minimumSquareMiles);
        }

        private void QueryByArea(int minimumSquareMiles)
        {
            var queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
            queryTask.ExecuteCompleted += QueryAreaTask_ExecuteCompleted;
            queryTask.Failed += (sender, args) => MessageBox.Show("Query failed: " + args.Error);

            var query =
                new Query
                {
                    Where = "SQMI > " + minimumSquareMiles,
                    ReturnGeometry = true,
                    OutFields = new OutFields { "*" },
                    OutSpatialReference = MapControl.SpatialReference
                };

            queryTask.ExecuteAsync(query);
        }

        private void QueryAreaTask_ExecuteCompleted(object sender, QueryEventArgs args)
        {
            var featureSet = args.FeatureSet;

            if (featureSet == null || featureSet.Features.Count == 0)
                return;

            foreach (var feature in featureSet.Features)
            {
                feature.Symbol = LayoutRoot.Resources["ResultsFillSymbol"] as FillSymbol;
                _selectionGraphicsLayer.Graphics.Add(feature);
            }
        }
    }
}
